package com.am.server.api.system.dictionary.service.impl;

import com.am.server.api.system.dictionary.dao.rdb.DictionaryDao;
import com.am.server.api.system.dictionary.model.dto.DictionaryDto;
import com.am.server.api.system.dictionary.model.dto.DictionaryListQueryDto;
import com.am.server.api.system.dictionary.model.dto.SaveDictionaryDto;
import com.am.server.api.system.dictionary.model.dto.UpdateDictionaryDto;
import com.am.server.api.system.dictionary.model.entity.DictionaryEntity;
import com.am.server.api.system.dictionary.model.mapper.DictionaryMapper;
import com.am.server.api.system.dictionary.service.DictionaryService;
import com.am.server.common.base.model.dto.PageDto;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

/**
 * @author 阮雪峰
 */
@Service
public class DictionaryServiceImpl implements DictionaryService {
    private final DictionaryDao dictionaryDao;
    private final DictionaryMapper dictionaryMapper;

    public DictionaryServiceImpl(DictionaryDao dictionaryDao, DictionaryMapper dictionaryMapper) {
        this.dictionaryDao = dictionaryDao;
        this.dictionaryMapper = dictionaryMapper;
    }

    @Override
    public PageDto<DictionaryDto> find(DictionaryListQueryDto dto) {
        Page<DictionaryEntity> page = dictionaryDao.findAll(dto);
        return new PageDto<DictionaryDto>()
                .setPage(dto.getPage())
                .setPageSize(dto.getPageSize())
                .setTotal((int) page.getTotalElements())
                .setTotalPage(page.getTotalPages())
                .setRows(page.getContent().stream().map(dictionaryMapper::toDto).toList());
    }

    @Override
    public void save(SaveDictionaryDto dto) {
        dictionaryDao.save(dictionaryMapper.saveDtoToEntity(dto));
    }

    @Override
    public void update(UpdateDictionaryDto dto) {
        dictionaryDao.findById(dto.getId())
                .ifPresent(entity -> {
                    entity.setCode(dto.getCode());
                    entity.setName(dto.getName());
                    entity.setMemo(dto.getMemo());

                    dictionaryDao.save(entity);
                });
    }

    @Override
    public void delete(Long id) {
        dictionaryDao.deleteById(id);
    }

    @Override
    public Boolean exist(String code) {
        return dictionaryDao.findByCode(code).isPresent();
    }

    @Override
    public Boolean exist(String code, Long id) {
        return dictionaryDao.findByCodeWithId(code, id).isPresent();
    }
}
